package com.li.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.aliyuncs.exceptions.ClientException;
import com.li.constant.MessageConstant;
import com.li.entity.Result;
import com.li.pojo.Order;
import com.li.service.OrderService;
import com.li.utils.RedisMessageConstant;
import com.li.utils.SMSUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.JedisPool;

import java.util.Map;

@RestController
@RequestMapping("/order")
public class OrderController {

    @Reference
    OrderService orderService;
    @Autowired
    JedisPool jedisPool;
    @RequestMapping("/submit")
    public Result submitOrder(@RequestBody Map map){
        String telephone = (String) map.get("telephone");
        //校验验证码
        String validateCode = (String) map.get("validateCode");
        String codeInRedis = jedisPool.getResource().get(telephone + RedisMessageConstant.SENDTYPE_ORDER);

        if(codeInRedis==null||!codeInRedis.equals(validateCode)){
            return new Result(false, MessageConstant.VALIDATECODE_ERROR);
        }

        //调用体检预约服务
        Result result=null;
        try {
            map.put("orderType", Order.ORDERTYPE_WEIXIN);
            result=orderService.order(map);
        }catch (Exception e){
            e.printStackTrace();
            return new Result(false,"预约失败");
        }

        //判断是否预约成功 发送短信进行通知
        if(result.isFlag()){
            try {
                //预约成功 发送短信通知
                String orderDate = (String) map.get("orderDate");
                String[] split = orderDate.split("-");
                orderDate=split[1]+"005"+split[2];
                SMSUtils.sendShortMessage(SMSUtils.VALIDATE_CODE,telephone,orderDate);
            } catch (ClientException e) {
                e.printStackTrace();
            }
        }

        return result;
    }

    @RequestMapping("/findById")
    public Result findById(String id){

        //通过id获取体检人 体检套餐 体检日期 预约方式
        //需要操作三张表 order体检日期  预约方式  setmeal体检套餐 member 体检人
        try {
            Map map = orderService.findById(Integer.parseInt(id));

            return new Result(true,MessageConstant.QUERY_ORDER_SUCCESS,map);
        }catch (Exception e){
            e.printStackTrace();
            return new Result(false,MessageConstant.QUERY_ORDER_FAIL);
        }


    }
}
